package com.example.bdd.demo.base;

import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import com.example.bdd.demo.base.config.BddBaseConfig;

import java.util.*;

public class BddBaseService {

    private WebDriver webDriver;
    private String main_windows;

    public void load(String domain) {
        webDriver = BddBaseConfig.getInstance(domain);
    }

    public void setFieldValue(By byKey, String content) {
        findElement(byKey).sendKeys(content);
    }

    public String getFieldValue(By byKey) {
        return webDriver.findElement(byKey).getText();
    }

    public WebElement findElement(By byKey) {
        return webDriver.findElement(byKey);
    }

    public List<String> getFieldsValue(By byKey) {
        List<WebElement> elements = webDriver.findElements(byKey);
        List<String> getFieldsValue = new ArrayList<>();
        elements.forEach(e -> getFieldsValue.add(e.getText()));
        return getFieldsValue;
    }

    public List<WebElement> findElements(By byKey) {
        return webDriver.findElements(byKey);
    }

    public void selectRadio(By byKey, int index) {
        webDriver.findElements(byKey).get(index).click();
    }

    public void clickButton(By byKey) {
        findElement(byKey).click();
    }

    public void toOpenLink(By byKey) {
        main_windows = webDriver.getWindowHandle();
        WebElement element = findElement(byKey);
        //element.click();
        String href = element.getAttribute("href");
        String js = "window.open('" + href + "');";
        jsExecutor(js, element);
    }

    public void closePage(boolean isAfterScenario) {
        String windows = webDriver.getWindowHandle();
        Set<String> windowHandles = webDriver.getWindowHandles();
        if (isAfterScenario) {
            windowHandles.forEach(w -> webDriver.close());
        } else {
            windowHandles.forEach(w -> {
                if (!w.equals(windows)) {
                    webDriver.switchTo().window(w);
                    webDriver.close();
                }
            });
            webDriver.switchTo().window(windows);
        }
    }

    public void jsExecutor(String js, WebElement element) {
        JavascriptExecutor jse = (JavascriptExecutor)webDriver;
        Actions actions = new Actions(webDriver);
        //actions.moveToElement(element).perform();
        actions.moveToElement(element);
        //jse.executeScript(js, new Object[]{element});
        jse.executeScript(js);
    }


}
